import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

class FileService {
  static const String baseUrl = 'http://39.107.246.135:1224';
  static const int timeoutSeconds = 10;

  // 上传文件
  static Future<Map<String, dynamic>> _uploadRequest({
    required String path,
    required File file,
    required String? token,
  }) async {
    try {
      final url = Uri.parse('$baseUrl$path');
      var request = http.MultipartRequest('POST', url);

      // 添加文件到请求
      request.files.add(
        await http.MultipartFile.fromPath(
          'file',
          file.path,
          contentType: MediaType('application', 'octet-stream'),//用于指定上传文件的 MIME 类型为通用二进制数据流。这在不知道文件具体类型时非常有用
        ),
      );

      // 设置请求头
      request.headers['Authorization'] = token!;

      // 发送请求
      var response = await request.send().timeout(
        const Duration(seconds: timeoutSeconds),
        onTimeout: () => throw TimeoutException('请求超时'),
      );

      // 处理响应
      final responseBody = await response.stream.bytesToString();
      return jsonDecode(responseBody);
    } on SocketException catch (e) {
      if (kDebugMode) {
        print('网络连接异常：$e');
      }
      return _errorResponse('无法连接到服务器，请检查：\n1. 网络连接\n2. 服务器地址\n3. 端口号');
    } on TimeoutException catch (e) {
      if (kDebugMode) {
        print('请求超时：$e');
      }
      return _errorResponse('服务器响应超时，请稍后重试');
    } on HttpException catch (e) {
      if (kDebugMode) {
        print('HTTP协议异常：$e');
      }
      return _errorResponse('服务器响应异常');
    } catch (e) {
      if (kDebugMode) {
        print('文件上传未知异常：$e');
      }
      return _errorResponse('未知错误：${e.toString()}');
    }
  }

  static Map<String, dynamic> _errorResponse(String message) {
    return {
      "code": -1,
      "message": message,
      "timestamp": DateTime.now().toIso8601String(),
    };
  }

  // 上传文件接口
  static Future<Map<String, dynamic>> uploadFile(File file, String? token) async {
    // if (kDebugMode) {
    //   print("得到token: $token");
    // }
    if (token == null || token.isEmpty) {
      return {"code": 40020, "message": "未授权，请先登录", "data": null};
    }
    return _uploadRequest(path: "/oss/upload", file: file, token: token);
  }

}
